package edu.pku.sei.autounit.generator;

import java.util.Map;

import edu.pku.sei.autounit.core.Variable;
import edu.pku.sei.autounit.reflect.Method;
import edu.pku.sei.autounit.reflect.Type;
import edu.pku.sei.autounit.util.Statements;

public class ReturnValue implements Variable{

	private Type type;
	private String name;
	private Method method;
	private Variable runObject;
	private Variable [] parameters;
	
	public ReturnValue(Type type,String name,Method method,Variable runObject,Variable[] parameters) {
		this.method = method;
		this.type = type;
		this.name = name;
		this.runObject = runObject;
		this.parameters = parameters;
	}

	
	public Type getType() {
		return type;
	}

	
	public String getValue() {
		return name;
	}
	
	
	public Statements getInitCode(Map<String,String> map){
		Statements s = new Statements();
		
		if(!method.isStatic()){
			s.merge(runObject.getInitCode(map));
		}
		
		for(Variable p:parameters){
			s.merge(p.getInitCode(map));
		}
		
		if(method.hasException()){
			s.insertStatement(type.getName(map)+" "+name+" = null;");
			s.insertStatement("try{");
		}
		
		StringBuffer sb=new StringBuffer();
		if(!method.hasException()){
			sb.append(type.getName(map)+" ");
		}
		sb.append(name+" = ");
		if(method.isStatic())
			sb.append(method.getDeclaringClass().getName(map));
		else
			sb.append(runObject.getValue());
		
		sb.append("."+method.getName()+"(");
		
		for(Variable v:parameters){
			sb.append(v.getValue()+",");
		}
		
		String temp = sb.toString();
		if(temp.endsWith(","))
			s.insertStatement(temp.substring(0, temp.length()-1)+");");
		else
			s.insertStatement(temp.substring(0, temp.length())+");");
		
		if(method.hasException()){
			s.insertStatement("}catch(Throwable e){");
			s.insertStatement("fail();");
			s.insertStatement("}");
		}
		return s;
	}
}